<template>
  <div class="operate-wrapper">
    <a-space>
      <a-button type="primary" @click="handleAdd('0', '-1')">
        <template #icon>
          <PlusOutlined />
        </template>新增
      </a-button>
    </a-space>
  </div>
  <a-table :columns="columns" :data-source="tableData" :pagination="false">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-space>
          <a-button type="link" size="small" @click="handleAuth">【授权】</a-button>
          <a-button type="link" size="small" @click="handleAdd('0', record.value)">【新增】</a-button>
          <a-button type="link" size="small" @click="handleUpdate(record.value)">【修改】</a-button>
          <a-popconfirm title="是否删除?" cancelText="取消" okText="确认" @confirm="() => handleDelete(record.value)">
            <a-button type="link" danger size="small">【删除】</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>
  <DataForm ref="dataForm" @ok="handleRefresh" />
  <AuthForm ref="authForm" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getAllTree, remove, getById } from '@/api/menu/index'
import DataForm from './modules/DataForm.vue'
import AuthForm from './modules/AuthForm.vue'

onMounted(() => {
  handleRefresh()
})

const dataForm = ref()
const authForm = ref()
const tableData = ref([])
const columns = ref([
  { title: '菜单名称', dataIndex: 'title', key: 'title', ellipsis: true },
  { title: '菜单地址', dataIndex: 'url', key: 'url', ellipsis: true },
  { title: '排序', dataIndex: 'order', key: 'order', width: 100, ellipsis: true },
  { title: '操作', dataIndex: 'action', width: 340, align: 'center', key: 'action' }
])

const handleAuth = () => {
  authForm.value.show()
}

const handleAdd = (type, parentId) => {
  dataForm.value.add(type, parentId)
}

const handleUpdate = (menuId) => {
  getById(menuId).then((res) => {
    if (res.code === 0) {
      dataForm.value.edit('1', res.data)
    } else {
      message.error(res.message)
    }
  })
}

const handleDelete = (menuId) => {
  remove(menuId).then((res) => {
    if (res.code === 0) {
      if (res.data) {
        message.success('操作成功！')
      } else {
        message.danger('操作失败！')
      }
      handleRefresh()
    } else {
      message.error(res.message)
    }
  })
}

const handleRefresh = () => {
  getAllTree().then((res) => {
    if (res.code === 0) {
      tableData.value = res.data
    }
  })
}
</script>
<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'menu_info'
})
</script>